package fragment.tabhostFragment;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lanou.horo.myapplication.R;

import java.util.Random;

import entity.HotFindListResult;
import entity.SearchEntity;
import fragment.AbsBaseFragment;
import fragment.recommendfragments.ReCommendDetailsFragment;
import utils.texttools.KeywordsFlow;
import utils.adapter.SearchListAdapter;
import utils.texttools.StringUtil;
import volley.VolleySingleton;

/**
 * Created by dllo on 15/11/28.
 */
public class SearchFragment extends AbsBaseFragment implements TextWatcher, View.OnClickListener, View.OnFocusChangeListener {
    private EditText search_Et;
    private KeywordsFlow keywordsFlow;
    private Button cancle_btn;
    public String[] keywords;
    private ListView searchListView;
    private SearchListAdapter searchListAdapter;
    private SearchEntity sea;

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_search;
    }

    @Override
    protected void initView() {
        search_Et = findView(R.id.search_Et);
        keywordsFlow = findView(R.id.keywordsFlow);
        cancle_btn = findView(R.id.find_cancle);
        searchListView = findView(R.id.searchListView);
    }

    @Override
    protected void initData() {
        searchListAdapter = new SearchListAdapter(getContext());
        keywordsFlow.setOnItemClickListener(this);
        search_Et.addTextChangedListener(this);
        cancle_btn.setOnClickListener(this);
        search_Et.setOnFocusChangeListener(this);
        keywordsFlow.setDuration(800l);
        searchListView.setAdapter(searchListAdapter);
        searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (sea.getAlbumResultList() != null) {
                    if (sea.getAlbumResultList().size() > position)
                        goToNext(new ReCommendDetailsFragment(sea.getAlbumResultList().get(position).getId(), 1));
                }
            }
        });
        initNetWork();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        searchListAdapter.cleanList();
    }

    @Override
    public void afterTextChanged(Editable s) {
        String tag = search_Et.getText().toString();
        String seaUrl = StringUtil.utf8Encode(tag);
        if (!StringUtil.isEmpty(seaUrl)) {
            String searchUrl = "http://search.ximalaya.com/suggest?device=android&kw=" + seaUrl;
            initSearch(searchUrl);
        }else {
            searchListView.setVisibility(View.GONE);
            keywordsFlow.setVisibility(View.VISIBLE);
        }
    }
    private void initSearch(String searchUrl) {
        VolleySingleton.getInstance().addRequest(searchUrl,
                SearchEntity.class, new Response.Listener<SearchEntity>() {
                    @Override
                    public void onResponse(SearchEntity response) {
                        if (response != null) {
                            searchListAdapter.addData(response);
                            sea = response;
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
    }
    private void feedKeywordsFlow(KeywordsFlow keywordsFlow, String[] arr) {
        Random random = new Random();
        for (int i = 0; i < KeywordsFlow.MAX; i++) {
            int ran = random.nextInt(arr.length);
            String tmp = arr[ran];
            keywordsFlow.feedKeyword(tmp);
        }
    }

    @Override
    public void onClick(View v) {
        if (v == cancle_btn) {
            goBack();
        } else if (v instanceof TextView) {
            String keyword = ((TextView) v).getText().toString();
            search_Et.setText(keyword);
            searchListView.setVisibility(View.VISIBLE);
            keywordsFlow.setVisibility(View.GONE);
        }
    }

    public void initNetWork() {
        String URL = "http://mobile.ximalaya.com/s/hot_search_key?device=android&size=10";
        VolleySingleton.getInstance().addRequest(URL,
                HotFindListResult.class, new Response.Listener<HotFindListResult>() {
                    @Override
                    public void onResponse(HotFindListResult response) {
                        if (response != null) {
                            initKeyWord(response);
                            if (keywords != null)
                                feedKeywordsFlow(keywordsFlow, keywords);
                            keywordsFlow.go2Show(KeywordsFlow.ANIMATION_IN);
                        }
                        dismissDialog();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        toastError();
                        dismissDialog();
                    }
                });
        showDialog();
    }

    private void initKeyWord(HotFindListResult response) {
        keywords = new String[response.getList().size()];
        for (int i = 0; i < response.getList().size(); i++) {
            keywords[i] = response.getList().get(i);
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        searchListView.setVisibility(View.VISIBLE);
        keywordsFlow.setVisibility(View.GONE);
    }
}
